// import Cookies from 'js-cookie';
import type { FormRules } from 'element-plus'
import type { ComputedRef, MaybeRefOrGetter } from 'vue'
import { UserInfoEnum } from '@/enum'
import type { UserLoginParams } from '@/types'

export const foremRules: FormRules = {
  loginName: [{ required: true, message: '用户名不能为空！', trigger: 'blur' }],
  passWord: [
    {
      required: true,
      message: '密码不能为空！',
      trigger: 'blur',
    },
  ],
}

/** 记住的登录成功历史账号和密码（加密） */
export function useHistoricalUsers(isRemember: MaybeRefOrGetter<boolean>, loginForm: ComputedRef<UserLoginParams>) {
  let cache = []
  try {
    // cache = JSON.parse(Cookies.get(UserInfoEnum.USER) || '') || [];
    cache = JSON.parse(localStorage.getItem(UserInfoEnum.USER) || '') || []
  }
  catch (e) {}
  const users = ref<UserLoginParams[]>(cache)

  function update() {
    const shouldCache = toValue(isRemember)
    const info = toValue(loginForm)
    const caches = toValue(users)
    const target = caches.find(v => v.loginName === info.loginName)

    if (target) {
      caches.splice(caches.indexOf(target), 1)
    }

    shouldCache && caches.unshift(info)
    // console.log('caches: ', caches);

    users.value = caches
    // Cookies.set(UserInfoEnum.USER, JSON.stringify(caches));
    localStorage.setItem(UserInfoEnum.USER, JSON.stringify(caches))
  }

  return {
    users,
    update,
  }
}
